import React, { Component } from 'react';
import { Icon, message } from 'antd';
import { connect } from 'dva';
import style from './Feedback.less';
import FeedbackModal from './FeedbackModal.js';

class Feedback extends Component {

  constructor(props) {
    super(props);
    this.state = {
      shouldUpdate: false,
      isFeedbackShow: false
    }
  }

  shouldComponentUpdate(nextProps, nextState) {
    // 只有提交反馈成功或内部state改变时true
    if (nextProps.global.shouldUpdate || nextState.shouldUpdate) {
      this.form.resetFields();
      return true;
    } else {
      return false;
    }
  }

  componentWillReceiveProps(nextProps) {
    const msg = nextProps.global.message;
    const oldMsg = this.props.global.message;
    // 利用Symbol类型的key解决消息重复的问题
    if (msg.key !== oldMsg.key) {
      if (msg.type == 'success') {
        message.success(msg.msg, 4);
      } else if (msg.type == 'error') {
        message.error(msg.msg, 4);
      }
    }
    this.setState({
      shouldUpdate: false,
      isFeedbackShow: false
    });
  }

  showFeedbackModal = () => {
    this.setState({
      shouldUpdate: true,
      isFeedbackShow: true
    });
  }

  handleCancel = () => {
    this.setState({
      shouldUpdate: true,
      isFeedbackShow: false
    });
  }

  onFeedback = () => {
    const form = this.form;
    form.validateFields((err, values) => {
      if (err) {
        return;
      }
      this.props.dispatch({
        type: 'global/submitFeedback',
        payload: values
      });
    });
  }

  saveFormRef = (form) => {
    this.form = form;
  }

  render() {
    return(
      <div title="反馈" onClick={this.showFeedbackModal} className={style.feedback_wrap}>
        <Icon type="message" />
        <FeedbackModal
          ref={this.saveFormRef}
          visible={this.state.isFeedbackShow}
          handleCancel={this.handleCancel}
          onFeedback={this.onFeedback}
        />
      </div>
    );
  }
}

function mapStateToProps(global) {
  return {...global};
}

export default connect(mapStateToProps)(Feedback);